package com.mvc.server.miaosha.rabbitmq;

import javax.annotation.Resource;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.mvc.server.miaosha.common.CommonContant;
import com.mvc.server.miaosha.common.CommonUtil;
import com.mvc.server.miaosha.pojo.MiaoshaOrder;
import com.mvc.server.miaosha.pojo.MiaoshaUser;
import com.mvc.server.miaosha.service.GoodsService;
import com.mvc.server.miaosha.service.MiaoshaService;
import com.mvc.server.miaosha.service.OrderService;
import com.mvc.server.miaosha.vo.GoodsVo;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service
public class MQReceiver {

		@Resource
		private GoodsService goodsService;
		
		@Resource
		private OrderService orderService;
		
		@Resource
		private MiaoshaService miaoshaService;
		
		@RabbitListener(queues=CommonContant.MIAOSHA_QUEUE)
		public void receive(String message) {
			log.info("receive miaosha message:"+message);
			MiaoshaMessage mm  = CommonUtil.stringToBean(message, MiaoshaMessage.class);
			MiaoshaUser user = mm.getUser();
			long goodsId = mm.getGoodsId();
			
			GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
	    	int stock = goods.getStockCount();
	    	if(stock <= 0) {
	    		return;
	    	}
	    	//判断是否已经秒杀到了
	    	MiaoshaOrder order = orderService.getCacheMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
	    	if(order != null) {
	    		return;
	    	}
	    	//减库存 下订单 写入秒杀订单
	    	miaoshaService.miaosha(user, goods);
		}

		@RabbitListener(queues=CommonContant.QUEUE)
		public void receive2(String message) {
			log.info("receive message:"+message);
		}
//		
//		@RabbitListener(queues=CommonContant.TOPIC_QUEUE1)
//		public void receiveTopic1(String message) {
//			log.info(" topic  queue1 message:"+message);
//		}
//		
//		@RabbitListener(queues=CommonContant.TOPIC_QUEUE2)
//		public void receiveTopic2(String message) {
//			log.info(" topic  queue2 message:"+message);
//		}
//		
//		@RabbitListener(queues=CommonContant.HEADER_QUEUE)
//		public void receiveHeaderQueue(byte[] message) {
//			log.info(" header  queue message:"+new String(message));
//		}
//		
		
}
